package com.example.library.controller;

import com.example.library.entity.BorrowRecord;
import com.example.library.service.BorrowService;
import com.example.library.repository.UserRepository;
import com.example.library.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/borrows")
public class BorrowController {
    @Autowired
    private BorrowService borrowService;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private BookRepository bookRepository;

    @GetMapping
    public List<BorrowRecord> list() {
        return borrowService.findAll();
    }

    @PostMapping
    public BorrowRecord add(@RequestBody BorrowRecord record) {
        // 只传了id时，需查出完整对象
        if (record.getUser() != null && record.getUser().getId() != null) {
            userRepository.findById(record.getUser().getId()).ifPresent(record::setUser);
        }
        if (record.getBook() != null && record.getBook().getId() != null) {
            bookRepository.findById(record.getBook().getId()).ifPresent(record::setBook);
        }
        try {
            return borrowService.save(record);
        } catch (RuntimeException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    @PutMapping("/{id}")
    public BorrowRecord update(@PathVariable Integer id, @RequestBody BorrowRecord record) {
        record.setId(id);
        if (record.getUser() != null && record.getUser().getId() != null) {
            userRepository.findById(record.getUser().getId()).ifPresent(record::setUser);
        }
        if (record.getBook() != null && record.getBook().getId() != null) {
            bookRepository.findById(record.getBook().getId()).ifPresent(record::setBook);
        }
        return borrowService.save(record);
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Integer id) {
        borrowService.deleteById(id);
    }

    @GetMapping("/by-user")
    public List<BorrowRecord> findByUserId(@RequestParam Integer userId) {
        return borrowService.findByUserId(userId);
    }
}
